<?php

	class Application {
		
		function run($args) {
			session_start();
			
			if (isset($_GET['page'])) {
				$url = $_GET['page'];
			} else {
				list($param_name,$param_value) = each($_GET); reset($_GET); if (empty($param_value)) $url = $param_name;
			}	
				
			if (empty($url)) $url = 'home';
			
			require_once('content/pages.php');
			if (!isset($pages[$url])) die($this->flashError('./', '', '70'));
			
			$page = $pages[$url];		
			$this->page = $page;
			
			# get template
			$template_name = $page['template'];
			$template_file = 'php/templates/' . $template_name . '_template.php';
			require_once($template_file);
			$template_class = $template_name . 'Template';
			$template = new $template_class();
			
			$template->application = $this;
			$template->page = $page;
				
			$this->template = $template;
	
			# run controller
			$controller_name = $page['controller'];
			$action_name = $page['action'];
			$controller_dir = $page['controller_dir'];
			
			if ($_POST && $page['post_action']) 
				$action_name = $page['post_action'];
				
			
			if (empty($controller_dir) or empty($controller_name)) $controller_dir = '';
			else $controller_dir.='/';
			if (empty($controller_name)) $controller_name = 'default';
			if (empty($action_name)) $action_name = 'view';
			
			$controller_class = $controller_name . 'Controller';
			$controller_file = 'php/controllers/' .$controller_dir. $controller_name . '_controller.php';
			
			require_once($controller_file);
			$controller = new $controller_class();
			$controller->application = $this;
			$controller->database = $this->database;
			$controller->user = $this->user;
	
			if (method_exists($controller, 'init')) $controller->init();
			
			$view = $controller->$action_name($page);
			if ($page[controller] <> 'xmlinterface'){
				
				if (!$view) die('No view returned by controller');
			
				# render template
				$template->content = $view->content();
				$template->user = $this->user;
				$template->render();
			}	
		}

		/**
		 * Shows message and then allows user to continue. Does not return.
		 *
		 * @access public
		 */
		function flashError($redirect, $failmessage = '', $failcode) {
			require_once('php/views/yapter_view.php');
			$view =& new YapterView('content/error.tpl');
			if ($GLOBALS['debug'] == false) {
				$view->set('redirect', $redirect);
			}
			
			require('php/config/error.php');
			$view->set('failcode', $failcode);
			if ($failmessage == '') {
				$view->set('failmessage', $error[$failcode]);
			} else {
				$view->set('failmessage', $failmessage);
			}
			
			$view->render();
	
			exit();
		}
	}
?>